//
//  YBMessageListVC.swift
//  Moonlight
//
//  Created by 清风徐来 on 2023/7/4.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import EachNavigationBar
import HandyJSON
import SwiftyJSON
import JXPagingView
import JXSegmentedView

class YBMessageListVC: BaseVC {
    
    fileprivate var pageNo = 1
    fileprivate var pageSize = 10
    
    deinit {
        listViewDidScrollCallback = nil
    }
    
    private var listViewDidScrollCallback: ((UIScrollView) -> ())?
    
    private let itemType: YBMessageVC.ItemType
    
    // MARK: - lazy
    lazy var vm: YBMessageViewModel = {
        let vm = YBMessageViewModel()
        return vm
    }()

    private lazy var tableView: BKGestureTableView = {
        let tv = BKGestureTableView(frame: .zero, style: .grouped)
        tv.estimatedRowHeight = 44
        tv.rowHeight = UITableView.automaticDimension
        tv.delegate = self
        tv.dataSource = self
        tv.separatorStyle = .none
        tv.backgroundColor = .clear
        tv.showsVerticalScrollIndicator = false
        tv.tableFooterView = UIView()
        if #available(iOS 15.0, *) {
            tv.sectionHeaderTopPadding = 0
        }
        tv.bk_addRefreshHeader { [weak self] in
            self?.headerRefresh()
        }
        tv.bk_addLoadMoreFooter { [weak self] in
            self?.footerRefresh()
        }
        tv.bkFooter?.isHidden = true
        tv.register(nib: UINib.init(nibName: "YBMessageCell", bundle: nil), withCellClass: YBMessageCell.self)

        return tv
    }()
    
    init(type: YBMessageVC.ItemType) {
        itemType = type
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .lightGray242Dark17

        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 占位图
        showEmptyData(self.tableView)
        // 开始请求
        tableView.bk_refreshing()
    }

    func headerRefresh() {
        pageNo = 1
        // 请求数据
        let params = ["pageNo": pageNo.stringValue(),
                      "pageSize": pageSize.stringValue(),
                      "sortType": 0,
                      "status": 1,
                      "title": "",
                      "type": itemType.rawValue.stringValue()] as [String : Any]
        
        vm.req_messageListInfo(params) { [weak self] ok, obj, msg, code in
            self?.tableView.bk_endMJRefresh()
            if ok {
                guard let js = obj as? JSON,
                      let data = js[NetDataKey]["list"].arrayObject,
                      let total = js[NetDataKey]["total"].int,
                      let models = [YBMessageModel].deserialize(from: data) as? [YBMessageModel] else { return }
                
                if (total / self!.pageSize) > self!.pageNo {
                    self?.tableView.bkFooter?.isHidden = false
                }
                self?.vm.messageModels = models
                self?.tableView.reloadData()
            } else {
                HintTool.toast(msg)
            }
        }
    }
    
    func footerRefresh() {
        pageNo += 1
        // 请求数据
        let params = ["pageNo": pageNo.stringValue(),
                      "pageSize": pageSize.stringValue(),
                      "sortType": 0,
                      "status": 1,
                      "title": "",
                      "type": itemType.rawValue.stringValue()] as [String : Any]
        
        vm.req_messageListInfo(params) { [weak self] ok, obj, msg, code in
            self?.tableView.bk_endMJRefresh()
            if ok {
                guard let js = obj as? JSON,
                      let data = js[NetDataKey]["list"].arrayObject,
                      let models = [YBMessageModel].deserialize(from: data) as? [YBMessageModel] else { return }
                self?.vm.messageModels.append(contentsOf: models)
                self?.tableView.reloadData()
            } else {
                HintTool.toast(msg)
            }
        }
    }
    
}


// MARK: - UITableView代理
extension YBMessageListVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return vm.messageModels.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YBMessageCell.self, for: indexPath)
        let model = vm.messageModels[indexPath.section]
        cell.updateCell(by: model)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        
        // 查询详情
        let model = vm.messageModels[indexPath.section]
        vm.req_messageDetailInfo(model.id) { ok, obj, msg, code in
            if ok {
                guard let js = obj as? JSON,
                      let dic = js[NetDataKey].dictionaryObject,
                      let model = YBMessageModel.deserialize(from: dic) else { return }
                
                DispatchQueue.main.async {
                    YBMessagePopView.show(model: model)
                }
            } else {
                HintTool.toast(msg)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let shapeLayer = CAShapeLayer()
        cell.layer.mask = nil
        let bezierPath = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 4, height: 4))
        shapeLayer.path = bezierPath.cgPath
        cell.layer.mask = shapeLayer
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
    
}

// MARK: - JXPagingViewListViewDelegate代理
extension YBMessageListVC: JXPagingViewListViewDelegate {
    
    func listView() -> UIView {
        return view
    }
    
    func listScrollView() -> UIScrollView {
        return tableView
    }
    
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }
    
}
